package com.treeman.api.controller.user;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.treeman.api.ApiRequestError;
import com.treeman.api.ApiRequestError.ApiError;
import com.treeman.api.controller.ApiExceptionResolverController;
import com.treeman.api.json.user.UserJson;
import com.treeman.api.json.user.UserLocationJson;
import com.treeman.user.exception.UserNotFoundException;
import com.treeman.user.service.UserService;

@Controller
@RequestMapping("/api")
public class UserDataController extends ApiExceptionResolverController {

	private static Logger log = Logger.getLogger(UserDataController.class);

	@Autowired
	UserService userService;

	@RequestMapping(value = "/users/{username}", method = RequestMethod.GET)
	public @ResponseBody
	UserJson getUserData(@PathVariable String username)
			throws UserNotFoundException {

		log.debug("Getting userData. Username: " + username);
		UserJson user = userService.getUserJsonByUsername(username);
		return user;
	}

	@PreAuthorize("isAuthenticated()")
	@RequestMapping(value = "/users/{username}/location", method = RequestMethod.GET)
	public @ResponseBody
	UserLocationJson getUserCurrentLocation(@PathVariable String username,
			HttpServletResponse response) throws UserNotFoundException {

		log.debug("Getting user location. Username: " + username);

		String requesterUsername = SecurityContextHolder.getContext()
				.getAuthentication().getName();
		UserLocationJson location;
		try {
			location = userService.getUserLocationJson(username,
					requesterUsername);
			if (location == null) {
				response.setStatus(HttpServletResponse.SC_NOT_FOUND);
				return null;
			} else
				return location;
		} catch (UserNotFoundException e) {
			log.debug("User not found!!! " + username);
			response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return null;
		}
	}

	@ExceptionHandler(UserNotFoundException.class)
	@ResponseStatus(value = HttpStatus.NOT_FOUND)
	public @ResponseBody
	ApiRequestError handleUserNotFoundException(UserNotFoundException e) {
		log.warn("User not found: " + e.getLocalizedMessage());

		return new ApiRequestError(ApiError.NOT_FOUND, "User not found");
	}
}
